package com.kantboot.api.email.listener;

import cn.hutool.extra.mail.MailAccount;
import cn.hutool.extra.mail.MailUtil;
import com.alibaba.fastjson2.JSON;
import com.kantboot.api.email.domain.entity.ApiEmail;
import com.kantboot.api.email.event.SendEmailEvent;
import com.kantboot.api.email.repository.ApiEmailRepository;
import com.kantboot.api.email.setting.ApiEmailSetting;
import jakarta.annotation.Resource;
import jakarta.transaction.Transactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class SendEmailListener {

    @Resource
    private ApiEmailRepository repository;

    @Resource
    private ApiEmailSetting setting;

    @Async
    @Transactional
    @EventListener
    public void sendEmail(SendEmailEvent event) {
        ApiEmail apiEmail = event.getEmail();
        MailAccount mailAccount = setting.getMailAccount();
        MailUtil.send(mailAccount, apiEmail.getTo(), apiEmail.getSubject(), apiEmail.getContent(), apiEmail.getIsHtml());
        apiEmail.setStatusCode(ApiEmail.STATUS_CODE_SUCCESS);
        log.info("邮件发送成功：{}", JSON.toJSONString(apiEmail));
        // 更新邮件状态,没有用，因为是异步的，所以这里不会更新
        repository.save(apiEmail);
    }

}
